<template>
  <flexbox
    :style="{ height: contentHeight + 'px' }"
    class="main"
    orient="vertical"
    align="stretch"
  >
    <div class="title d-flex justify-content-between align-items-center">
      <div class="d-flex align-items-center">
        <span class="size-14 color-02">您当前所在位置：</span>
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/manage/business/custom-field' }"
            >业务设置</el-breadcrumb-item
          >
          <el-breadcrumb-item :to="{ path: '/manage/business/custom-field' }"
            >自定义字段</el-breadcrumb-item
          >
          <el-breadcrumb-item>字段分配-{{ tabName }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-button
        style="border-radius: 2px; background-color: #edf1fc"
        @click="handleCancel"
        icon="el-icon-arrow-left"
        >返回</el-button
      >
    </div>
    <el-container class="wrapper">
      <el-aside class="left">
        <div class="list-wrapper">
          <el-tree
            ref="tree"
            :data="showDepData"
            node-key="deptId"
            highlight-current
            default-expand-all
            :filter-node-method="filterNode"
            @node-click="changeDepClick"
            v-if="tabValue == 1"
          >
            <flexbox
              slot-scope="{ node }"
              :class="{ 'is-current': node.isCurrent }"
              class="node-data"
              style="width: 88%"
            >
              <span class="node-data__mark" />
              <el-tooltip
                class="item"
                :content="node.label"
                placement="top"
                effect="dark"
                v-if="node.label.length > 16"
              >
                <div
                  class="node-data__label text-one-line"
                  :class="{
                    'search-current':
                      options.labelSearch &&
                      node.label.includes(options.labelSearch),
                  }"
                >
                  {{ node.label }}
                </div>
              </el-tooltip>
              <div
                v-else
                class="node-data__label text-one-line"
                :class="{
                  'search-current':
                    options.labelSearch &&
                    node.label.includes(options.labelSearch),
                }"
              >
                {{ node.label }}
              </div>
            </flexbox>
          </el-tree>
          <!-- 角色列表 -->
          <div class="role-nav-box" v-if="tabValue == 0">
            <div
              v-for="(item, index) in tempRoleOptions"
              :key="index"
              :class="{
                'is-select': item.roleId == roleActive.roleId,
                'search-current':
                  options.labelSearch &&
                  item.roleName.includes(options.labelSearch),
              }"
              class="menu-item"
              @click="roleMenuSelect(item)"
            >
              {{ item.roleName }}
            </div>
          </div>
        </div>
      </el-aside>
      <el-aside class="right" :style="{ width: contentWidth + 'px' }">
        <el-tabs v-model="tabValue" @tab-click="tabClick">
          <el-tab-pane
            :label="item.name"
            :name="`${item.label}`"
            v-for="(item, index) in tableList"
            :key="index"
          >
            <div class="d-flex align-items-center mb-20 mt-10">
              <div class="d-flex align-items-center">
                <div class="ml-16" style="text-wrap: nowrap">
                  {{ tabValue === "1" ? "部门" : "角色" }}名称：
                </div>
                <div
                  class="sc-container el-input el-input--suffix"
                  style="width: 270px"
                >
                  <el-input
                    type="text"
                    placeholder="请输入搜索内容"
                    v-model="options.labelSearch"
                    clearable
                  />
                </div>
              </div>
              <div class="d-flex align-items-center ml-10">
                <div class="ml-16" style="text-wrap: nowrap">字段名称：</div>
                <div
                  class="sc-container el-input el-input--suffix"
                  style="width: 270px"
                >
                  <el-input
                    type="text"
                    placeholder="请输入搜索内容"
                    v-model="options.fieldSearch"
                    clearable
                  />
                </div>
                <el-button
                  type="button"
                  class="el-button el-button--primary"
                  style="margin-left: 16px"
                  icon="el-icon-search"
                  @click="submitQuery"
                  >搜索
                </el-button>
              </div>
            </div>
            <div class="customer-content">
              <el-table
                v-loading="loading"
                :data="tempTabData"
                :height="`calc(100vh - 350px)`"
                highlight-current-row
                style="width: 100%"
              >
                <el-table-column
                  prop="name"
                  label="字段名称"
                  show-overflow-tooltip
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="formType"
                  label="查看权限"
                  show-overflow-tooltip
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.canCheck"
                      active-color="#0066F9"
                      inactive-color="#999"
                      :disabled="!getCanOpreateRead(scope.row.operateType)"
                      @change="checkCheckboxChange(scope.row)"
                    >
                    </el-switch>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="deptNames"
                  label="编辑权限"
                  show-overflow-tooltip
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.canEdit"
                      active-color="#0066F9"
                      inactive-color="#999"
                      :disabled="!getCanOpreateEdit(scope.row.operateType)"
                      @change="editCheckboxChange(scope.row)"
                    >
                    </el-switch>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
        <div
          class="dialog-footer d-flex justify-content-end align-items-center"
        >
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </el-aside>
    </el-container>
  </flexbox>
</template>

<script>
import { roleListAPI } from "@/api/admin/employeeDep"; // 角色列表
import { depListAPI } from "@/api/common"; // 获取部门接口
import {
  systemRoleGetFieldAPI,
  systemDepGetFieldAPI,
  systemRoleSetFieldAPI,
  systemDepSetFieldAPI,
} from "@/api/admin/role";
export default {
  name: "fieldAllocation",
  data() {
    return {
      contentHeight: document.documentElement.clientHeight - 75,
      contentWidth: "",
      showDepData: [], // 部门数据
      roleOption: [], // 角色数据
      tempRoleOptions: [], // 全部角色数据
      tabData: [], // 列表字段数据
      tempTabData: [], // 模板列表字段
      roleActive: {}, // 选中的角色
      depActive: {}, // 选中的部门
      tableList: [
        {
          name: "按照角色分配",
          label: "0",
        },
        {
          name: "按照部门分配",
          label: "1",
        },
      ], // tab切换数据
      options: {
        fieldSearch: "",
        labelSearch: "",
      }, // 查询参数
      loading: false,
      acitveTabValue: "", // 数据下标
      tabValue: "0", // tab下标
    };
  },
  computed: {
    tabName() {
      return this.acitveTabValue == 1
        ? "线索管理"
        : this.acitveTabValue == 2
        ? "学员管理"
        : this.acitveTabValue == 6
        ? "合同管理"
        : this.acitveTabValue == 7
        ? "回款管理"
        : this.acitveTabValue == 19
        ? "VIP学员管理"
        : this.acitveTabValue == 25
        ? "退款管理"
        : "";
    },
  },
  async mounted() {
    window.onresize = () => {
      this.contentHeight = document.documentElement.clientHeight - 75;
      this.contentWidth =
        document.getElementsByClassName("wrapper")[0].clientWidth - 315;
    };
    this.contentWidth =
      document.getElementsByClassName("wrapper")[0].clientWidth - 315;
    this.acitveTabValue = this.$route.params.label;
    await this.getRoleList(); // 获取角色列表
    // 初始化选择角色第一项
    this.roleActive = this.roleOption[0];
    await this.getDepList(); // 获取部门列表
    this.getDetaile(); // 获取字段信息
  },
  methods: {
    // 提交
    submit() {
      let list = this.tempTabData;
      let require = "";
      // 角色
      if (this.tabValue == "0") {
        require = systemRoleSetFieldAPI;
      } else if (this.tabValue == "1") {
        require = systemDepSetFieldAPI;
      }
      list.forEach((item) => {
        let authLevel = 3;
        if (item.canCheck && item.canEdit) {
          authLevel = 3;
        } else if (item.canCheck) {
          authLevel = 2;
        } else {
          authLevel = 1;
        }
        item.authLevel = authLevel;
      });
      require(list)
        .then((res) => {
          if (res && (res.code == 0 || res.code == 200)) {
            this.loading = false;
            this.$message.success("操作成功");
            // this.handleCancel();
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    /**
     * 获取列表字段数据
     */
    getDetaile() {
      this.loading = true;
      const params = { label: this.acitveTabValue };
      let require = "";
      // 角色
      if (this.tabValue == "0") {
        params.roleId = this.roleActive.roleId;
        require = systemRoleGetFieldAPI;
      } else if (this.tabValue == "1") {
        // 部门
        params.deptId = this.depActive.deptId;
        require = systemDepGetFieldAPI;
      }
      require(params).then((res) => {
        this.loading = false;
        const list = res.data || [];
        // authLevel 1 不能查看不能编辑 2可查看  3 可编辑可查看
        list.forEach((item) => {
          item.canCheck = item.authLevel == 2 || item.authLevel == 3;
          item.canEdit = item.authLevel == 3;
        });
        this.tabData = list;
        this.tempTabData = list;
      });
    },
    /**
     * 搜索
     */
    submitQuery() {
      console.log(this);
      const list = [];
      // 搜索字段名称
      if (this.options.fieldSearch) {
        this.tabData.forEach((item) => {
          if (item.name.includes(this.options.fieldSearch)) {
            list.push(item);
          }
        });
        this.tempTabData = list;
      } else {
        this.tempTabData = this.tabData;
      }
    },
    /**
     * tab点击
     */
    tabClick() {
      this.options.labelSearch = ""; // 清除搜索内容
      // 每次切换初始化数据
      if (this.tabValue == "0") {
        this.roleActive = this.roleOption[0];
      } else if (this.tabValue == "1") {
        this.depActive = this.showDepData[0];
      }
      this.getDetaile();
    },
    /**
     * 获取角色列表
     */
    async getRoleList() {
      const res = await roleListAPI({ querySuper: false });
      if (res) {
        this.tempRoleOptions = res.data[0].list;
        this.roleOption = this.tempRoleOptions;
        if (this.roleOption.length == 0 || !this.roleOption) {
          this.$message.error("暂无角色，请先添加角色");
          setTimeout(() => {
            this.$router.go(-1);
          }, 1000);
        }
      }
    },
    /**
     * 获取部门列表
     */
    async getDepList() {
      const res = await depListAPI({ type: "tree" });
      if (res) {
        this.showDepData = res.data || [];
      }
    },
    // 数据过滤方法
    filter(data) {
      const list = [];
      data.forEach((item) => {
        list.push(...item.list);
      });
      return list;
    },
    // 节点点击 部门
    changeDepClick(data) {
      this.depActive = data;
      this.getDetaile();
    },
    // 角色点击
    roleMenuSelect(val) {
      this.roleActive = val;
      this.getDetaile();
    },
    // 树形 过滤
    filterNode(value, data) {
      console.log(value, data);
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /**
     * 返回
     */
    handleCancel() {
      this.$router.go(-1);
    },

    // 1 都可以 2 能查看 3  能编辑 4  都不能
    getCanOpreateRead(operateType) {
      return operateType == 1 || operateType == 2;
    },

    getCanOpreateEdit(operateType) {
      return operateType == 1 || operateType == 3;
    },

    /**
     * 编辑有效时查看必须有效
     */
    editCheckboxChange(data) {
      if (data.canEdit) {
        this.$set(data, "canCheck", true);
      }
    },

    checkCheckboxChange(data) {
      if (!data.canCheck && data.canEdit) {
        this.$set(data, "canEdit", false);
      }
    },
  },
};
</script>

<style scoped lang="scss">
@import "@/styles/mixin.scss";

.el-form-item {
  margin: 0;
  padding-bottom: 16px;
  border-bottom: 1px solid $xr-border-line-color;
  .desc {
    color: #999;
    font-size: 12px;
  }
  &:last-child {
    margin-top: 15px;
  }
}

.title {
  padding: 0 16px;
  height: 55px;
  line-height: 60px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  background-color: #fff;
  border-bottom: 1px solid $xr-border-line-color;
}

.wrapper {
  background-color: white;
  // border: 1px solid $xr-border-line-color;
  // border-radius: $xr-border-radius-base;
  min-width: 1000px;
  overflow: hidden;
  flex: 1;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  -khtml-user-select: none;
  user-select: none;
  .left {
    min-width: 310px;
    .list-wrapper {
      padding: 20px 0;
      margin: 15px;
      background-color: #f5f6fb;

      .search-current {
        color: #ff6161;
      }
    }
  }

  .content {
    border-left: 1px solid $xr-border-line-color;
    border-right: 1px solid $xr-border-line-color;
    .el-header {
      border-bottom: 1px solid $xr-border-line-color;
      @include right;
    }
    .el-main {
      padding: 0;
      .selected {
        border-left: 2px solid $xr-color-primary;
        background: #f7f8fa;
      }
      .no-list {
        margin: 200px 0;
        color: #ccc;
        @include center;
      }
    }
  }

  .right {
    font-size: 14px;
    padding: 15px 15px 0 15px;
    box-sizing: border-box;
    .dialog-footer {
      height: 70px;
    }
  }
}

.role-nav-box {
  line-height: 30px;
  overflow-y: auto;
  height: calc(100% - 50px);
  background: #f5f6fb;
}
// 菜单
.menu-item {
  color: #333;
  font-size: 13px;
  padding: 0 15px;
  height: 40px;
  line-height: 40px;
  cursor: pointer;
  position: relative;
  .icon-close {
    position: absolute;
    top: 0;
    right: 8px;
    z-index: 1;
    display: none;
  }
}

.menu-item:hover,
.menu-item.is-select {
  background: #edf1fc;
  color: #0066f9;
}

.menu-item:hover::before,
.menu-item.is-select::before {
  content: " ";
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  width: 2px;
  background-color: #5383ed;
}

.role-nav-box .menu-item:hover .icon-close {
  display: block;
  float: right;
}

.el-tree {
  background: transparent;
}
.el-tabs {
  /deep/ .el-tabs__nav-wrap::after {
    // background-color: transparent;
  }
}

/deep/ .el-breadcrumb__separator {
  margin: 0;
}
</style>
